//导入express
const express = require('express');
const expressWs = require('express-ws');
const bodyParser = require('body-parser');
const cors = require('cors');
const path = require('path');
const { createProxyMiddleware } = require('http-proxy-middleware')
const chatModel = require('./modules/chat_tab')
const userModel = require('./modules/user_tab')
const app = express();
const { app: wsApp } = expressWs(app);
// 创建代理服务器，将请求转发到指定的URL
app.use(express.json({ limit: '50mb' }))
app.use(express.urlencoded({ limit: '50mb', extended: true }));
app.use(bodyParser.json());
app.use(cors());
// 给路由加前缀

//引入路由
const userRouter = require(path.join(__dirname,'router','user'))
const statisticsRouter = require(path.join(__dirname,'router','statistics'))
const tagRouter = require(path.join(__dirname,'router','tag'))
const triendRouter = require(path.join(__dirname,'router','triend'))
const commentRouter = require(path.join(__dirname,'router','comment'))
const chatRouter = require(path.join(__dirname,'router','chat'))
const imgRouter = require(path.join(__dirname,'router','img'))
app.use('/api/user',userRouter)
app.use('/api/statistics',statisticsRouter)
app.use('/api/tag',tagRouter)
app.use('/api/triend',triendRouter)
app.use('/api/comment',commentRouter)
app.use('/api/chat',chatRouter)
app.use('/api/img',imgRouter)
app.use(express.static('resource'))

wsApp.ws('/realtime/chat',(ws,req) => {
    ws.on('open',() => {
        console.log('建立了连接')
    })
    // 发送欢迎消息给当前用户
    ws.send(JSON.stringify({ type: 'welcome', content: `欢迎！` }));
      // 当接收到消息时
    ws.on('message', async(message) => {
        const data = JSON.parse(message)
        const chatAll = await chatModel.findAll({raw:true})
        const chat_id = chatAll.length>0? chatAll.sort((a, b) => b.chat_id - a.chat_id)[0].chat_id + 1  : 1
        const result1 = chatModel.create({
            chat_id,
            user1_id:data.user2_id,
            user2_id:data.user1_id,
            content:data.content,
            create_time:data.create_time
        })
        let result
       setTimeout(async() => {
        result = await chatModel.findAll({
            raw:true,
            where:{
                user1_id:data.user2_id,
                user2_id:data.user1_id,
                chat_id:chat_id
            },
            include: [
                { model: userModel, as: 'user1' },
                { model: userModel, as: 'user2' }
            ]
        })
        ws.send(JSON.stringify({ type: 'chatMessage', sender: data.user2_id, content: result }));
       },500)
       
      });
      // 当连接关闭时
      ws.on('close', () => {
        ws.close()
    })
})
app.listen(3000,() => {
    console.log("服务器启动成功: http://localhost:3000")
})



